#include "list.h"

void list_init(list_node * list)
{
    list->next = list;
    list->prev = list;
}

static void __list_add(list_node * node, list_node * prev, list_node * next) 
{
    next->prev = node;
    node->next = next;
    node->prev = prev;
    prev->next = node;
}

// 注: 任意的链表节点都可以作为head
void list_add(list_node * head, list_node * node)
{
    __list_add(node, head, head->next);
}

void list_tailadd(list_node * head, list_node * node)
{
    __list_add(node, head->prev, head);
}

static void __list_del(list_node * prev, list_node * next)
{
    prev->next = next;
    next->prev = prev;
}

void list_del(list_node * node)
{
    __list_del(node->prev, node->next);
}

bool list_empty(const list_node * head)
{
    return head->next == head;
}

bool list_one(const list_node * head)
{
    return !list_empty(head) && (head->prev == head->next);
}

// size_t offset = sizeof(type *) - sizeof(list_node);
// type * result = (type *)((uint8_t *)ptr - offset);
// 示例:
// size_t offset = sizeof(struct student) - sizeof(list_node);
// struct student * student = (struct student *)((uint8_t *)node - offset);
// 这种方式也可以,不过有限制, 结构体成员node必须放在结构体的最后.
// LIST_ENTRY的实现中则不存在这个问题.
